//
//  FormulaView.swift
//  DentalFormula
//
//  Created by AMalashin on 23.09.2023.
//

import SwiftUI

struct FormulaView: View {
    private let t = (1...8)
    @Binding var teeth: [Tooth]
    
    var body: some View {
        let index = dmfIndex()
        VStack {
            Text("Labelled \(teeth.count) teeth").font(.title)
            Text("DMF Index \(index[0])")//.font(.title2)
            Text("D:\(index[1]) M:\(index[2]) F:\(index[3])").font(.caption)
        }
        Grid(horizontalSpacing: 2, verticalSpacing: 2) {
            HStack {
                Text("1")
                Spacer()
                Text("2")
            }
            .padding(.horizontal)
            .font(.title)

            GridRow { // top row of teeth
                ForEach(t.reversed(), id: \.self) { col in ToothView(tooth: teeth.filter{$0.number == 10 + col}.first) } // 1
                Text("|")
                ForEach(t, id: \.self) { col in ToothView(tooth: teeth.filter{$0.number == 20 + col}.first) } // 2
            }

            GridRow { // row of numbers
                ForEach(t.reversed(), id: \.self) { col in Text("\(col)") }
                Text("|")
                ForEach(t, id: \.self) { col in Text("\(col)") }
            }.fontWeight(.bold)
            
            GridRow { // bottom row of teeth
                ForEach(t.reversed(), id: \.self) { col in ToothView(tooth: teeth.filter{$0.number == 40 + col}.first) } // 4
                Text("|")
                ForEach(t, id: \.self) { col in ToothView(tooth: teeth.filter{$0.number == 30 + col}.first) } // 3
            }

            HStack {
                Text("4")
                Spacer()
                Text("3")
            }
            .padding(.horizontal)
            .font(.title)
        }
    }
    
    private func dmfIndex() -> [Int] {
        var idxD: Int = 0
        var idxM: Int = 0
        var idxF: Int = 0

        for tooth in teeth {
            if tooth.number % 10 != 8 { // not a wisdom tooth
                if tooth.condition == .decay || tooth.condition == .decayFilling { idxD += 1 }
                if tooth.condition == .missed { idxM += 1 }
                if tooth.condition == .filling { idxF += 1 }
            }
        }

        return [idxD + idxM + idxF, idxD, idxM, idxF]
    }
}

/*

 8 7 6 5 4 3 2 1 | 1 2 3 4 5 6 7 8

 К D - кариес
 П F - пломба
 К/П D/F - кариес/пломба
 У M - удалён
 
 Индекс КПУ = К + П + У + К/П (без учёта 8к)
 DMF Index = ...
 
 Компонент К = сумма всех К + К/П (без 8)
 D (DMF) = ...
 
 Компонент У = сумма всех У (без 8)
 M (DMF) = ...
 
 Компонент П = сумма всех П (без 8)
 F (DMF)
 
*/

#Preview("Russian localization") {
    FormulaView(teeth: .constant(RandomData.generate())).environment(\.locale, .init(identifier: "ru"))
}

#Preview("English localization") {
    FormulaView(teeth: .constant(RandomData.generate())).environment(\.locale, .init(identifier: "en"))
}
